package cn.tedu.egmvc4.controller;

import cn.tedu.egmvc4.common.response.JsonResult;
import cn.tedu.egmvc4.common.response.StatusCode;
import cn.tedu.egmvc4.mapper.UserMapper;
import cn.tedu.egmvc4.pojo.dto.UserArticleDTO;
import cn.tedu.egmvc4.pojo.dto.UserLoginDTO;
import cn.tedu.egmvc4.pojo.entity.MvcArticle;
import cn.tedu.egmvc4.pojo.vo.ArticleVO;
import cn.tedu.egmvc4.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@RestController
@Api(tags = "01.用户模块")
@Slf4j
@RequestMapping("/v1/users/")
@Validated
public class UserController {

    @Autowired
    private UserMapper userMapper;


    @ApiOperation("登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.debug("userLoginDTO = " + userLoginDTO);

        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        UserVO userVO = userMapper.selectByUserNamePassword(username,password);

        if(userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }

        session.setAttribute("user",userVO);
        return JsonResult.ok();
    }

    @ApiOperation("发布文章功能")
    @PostMapping("article")
    public JsonResult insertArticle(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session){
        log.debug("userArticleDTO = " + userArticleDTO);

        MvcArticle mvcArticle = new MvcArticle();
        UserVO userVO = (UserVO) session.getAttribute("user");

        BeanUtils.copyProperties(userArticleDTO,mvcArticle);
        mvcArticle.setUserId(userVO.getId());
        userMapper.insertArticle(mvcArticle);

        return JsonResult.ok();
    }

    @ApiOperation("查询指定文章功能")
    @GetMapping("selectByArticleId")
    @ApiImplicitParam(name = "id", value = "文章id", required = true, dataType = "int")
    public JsonResult selectByArticleId(@Range(min = 1, max = 100, message = "文章id要求在1-100之间") @RequestParam Integer id){
        log.debug("id = " + id);

        ArticleVO articleVO = userMapper.selectByArticleId(id);

        return JsonResult.ok(articleVO);
    }
}
